package com.itunic.cloud.service;

import com.itunic.cloud.entity.UserDetailsEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * SpringSecurity 操作数据库加载用户数据的核心类
 * 通过UserDetailsService接口实现。
 * @author Sean
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    /**
     * 注入密码加密器
     */
    private PasswordEncoder passwordEncoder;

    public UserDetailsServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 该方法用于 通过登录用户名获取用户想干信息。
     * 如果用户存在，则将用户基本信息和权限信息交给
     * 框架处理。
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (log.isDebugEnabled()) {
            log.debug("登录用户名:{}", username);
        }
        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("用户不存在：" + username);
        }
        return buildUser("admin");
    }

    /**
     * 构造一个admin 用户，
     * 密码为 123456
     * 权限为：ROLE_ADMIN，ROLE_USER两个权限。
     * @param username
     * @return
     */
    private UserDetailsEntity buildUser(String username) {
        return new UserDetailsEntity("1",
                username,
                passwordEncoder.encode("123456"),
                //构造两个权限，role_admin,role_user
                AuthorityUtils.
                        commaSeparatedStringToAuthorityList(
                                "ROLE_ADMIN,ROLE_USER"));
    }
}